import Vue from "vue";

//引入路由
import VueRouter from "vue-router";

//引入组件
import Main from "../views/Main.vue";

//使用路由
Vue.use(VueRouter);

//将路由与组件进行映射
const routes = [
  //主路由
  {
    path: "/",
    component: Main,
    name: "Main",
    redirect: "/home",
    meta: { title: "首页" }, //路由源信息
    children: [
      //子路由
      // {
      //   path: "home",
      //   name: "home",
      //   meta: { title: "" },
      //   component: () => import("../views/Home.vue"),
      // }, //首页
      // {
      //   path: "user",
      //   name: "user",
      //   meta: { title: "用户" },
      //   component: () => import("../views/User.vue"),
      // }, //用户管理
      // {
      //   path: "mail",
      //   name: "mail",
      //   meta: { title: "商品管理" },
      //   component: () => import("../views/Mail.vue"),
      // }, //商品管理
      // {
      //   path: "page1",
      //   name: "page1",
      //   meta: { title: "page1" },
      //   component: () => import("../views/PageOne.vue"),
      // }, //页面1
      // {
      //   path: "page2",
      //   name: "page2",
      //   meta: { title: "page2" },
      //   component: () => import("../views/PageTwo.vue"),
      // }, //页面2
    ],
  },
  {
    path: "/login",
    name: "login",
    meta: { title: "login" },
    component: () => import("../views/Login.vue"),
  },
  {
    path: "/person",
    name: "person",
    meta: { title: "person" },
    component: () => import("../views/index.vue"),
  },
  {
    path: "/search",
    name: "search",
    meta: { title: "search" },
    component: () => import("../views/GitSearch.vue"),
  },
];

//先把VueRouter原型对象的push,保存一份
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;

//重写push|replace
//第一个参数：告诉原来的push方法，往哪里跳转（传递哪些参数）
//第二个参数：成功的回调
//第三个参数：失败的回调

VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    //call与apply的区别，
    //相同点，都可以调用函数一次，都可以篡改函数的上下文一次
    //不同点：call与apply传递参数：call传递多个参数用逗号隔开，apply方法执行传递多个参数用的是数组
    //此时originPush() 直接调用的话 this指向的是window 因此需要改变指向
    originPush.call(this, location, resolve, reject);
  } else {
    originPush.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};
VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject);
  } else {
    originReplace.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};

//创建router实例
const router = new VueRouter({
  routes, // (缩写) 相当于 routes: routes
  mode: "history",
  base: process.env.BASE_URL,
});
export default router;
